package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
	"react-blog-server/app/dao"
	"react-blog-server/app/dao/model"
	"react-blog-server/app/param"
	"react-blog-server/app/service"
	"react-blog-server/common/convert"
	"react-blog-server/common/response"
	"react-blog-server/common/util"
	"react-blog-server/config"
	"time"
)

func NewUserHttp(group *gin.RouterGroup) {
	group.GET("/user/info", GetUserInfo)
	group.PUT("/user/update", ModifyUserInfo)
	group.POST("/user/avatar", UpdateAvatar)
}

func UpdateAvatar(c *gin.Context) {
	userInfo, err := service.UserService.GetLoginUserInfo(c)
	if err != nil {
		response.Fail(c, http.StatusUnauthorized, "未登录，请先登录")
		return
	}

	file, err := c.FormFile("avatar")
	if err != nil {
		response.Fail(c, http.StatusBadRequest, "获取文件失败")
		return
	}

	now := time.Now()
	yyyy := now.Format("2006")
	MMdd := now.Format("0102")
	hh := now.Format("15")

	nano := convert.Int64ToString(now.UnixNano())
	userId := convert.Int64ToString(int64(userInfo.Id))

	path := "/Image/user/" + userId + "/" + yyyy + "/" + MMdd + "/" + hh + "/" + nano + "_" + file.Filename
	filePath := config.Cfg.Storage.Path + path
	fmt.Println("文件名：", filePath)

	dirName, fileName := filepath.Split(filePath)
	fmt.Println(dirName, fileName)

	if !util.IsPathExist(dirName) {
		err = os.MkdirAll(dirName, 0755)
		if err != nil {
			fmt.Printf("os.MkDirAll: %s, err: %s\n", dirName, err)
			response.Fail(c, http.StatusInternalServerError, "创建文件夹失败")
			return
		}
	}

	err = c.SaveUploadedFile(file, filePath)
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, "保存文件失败")
		return
	}

	// 更新用户头像
	avatar := "http://localhost:8080" + path
	err = dao.DB.Debug().Table("user").Where("id = ?", userInfo.Id).UpdateColumn("avatar", avatar).Error
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
		return
	}

	response.Success(c, avatar)
}

func GetUserInfo(c *gin.Context) {
	userInfo, err := service.UserService.GetLoginUserInfo(c)
	if err != nil {
		response.Fail(c, http.StatusUnauthorized, "未登录，请先登录")
		return
	}
	var user model.User
	if err := dao.DB.Where("id = ?", userInfo.Id).First(&user).Error; err != nil {
		response.Fail(c, http.StatusForbidden, "未找到该用户信息")
		return
	}
	user.Password = ""
	response.Success(c, &user)
}

func ModifyUserInfo(c *gin.Context) {
	userInfo, err := service.UserService.GetLoginUserInfo(c)
	if err != nil {
		response.Fail(c, http.StatusUnauthorized, "未登录，请先登录")
		return
	}
	var req param.ModifyUserInfoReq
	if err := c.BindJSON(&req); err != nil {
		response.Fail(c, http.StatusBadRequest, err.Error())
		return
	}
	err = dao.DB.Debug().Table("user").Where("id = ?", userInfo.Id).Updates(&req).Error
	if err != nil {
		response.Fail(c, http.StatusInternalServerError, err.Error())
		return
	}
	response.Ok(c)
}
